package com.gitee.feizns.web.utils;

import com.baomidou.mybatisplus.plugins.Page;
import com.gitee.feizns.web.domain.page.PageAo;
import com.gitee.feizns.web.domain.page.PageVo;
import com.gitee.feizns.web.domain.page.RowBoundsPageVoRet;
import com.gitee.feizns.web.domain.page.RowBoundsSameLayerPageVo;
import com.gitee.feizns.web.domain.page.TotalRowBounds;
import org.apache.ibatis.session.RowBounds;

import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author feizns
 * @since 2019/7/8
 */
public abstract class PageUtils {

    private static final int DEFAULT_START = 0;

    private static final int DEFAULT_PAGE_START = 1;

    private static final int DEFAULT_LIMIT = 10;

    /**
     * 默认以及相关优先级
     * @param pageAo
     * @return
     */
    public static final RowBounds toRowBounds(PageAo pageAo) {

        if ( pageAo.getOffset() != null && pageAo.getLimit() != null )
            return new TotalRowBounds(pageAo.getOffset(), pageAo.getLimit());

        if ( pageAo.getOffset() != null )
            return new TotalRowBounds(pageAo.getOffset(), DEFAULT_LIMIT);

        if ( pageAo.getLimit() != null )
            return new TotalRowBounds(DEFAULT_START, pageAo.getLimit());

        if ( pageAo.getCurrent() != null && pageAo.getSize() != null )
            return new Page(pageAo.getCurrent(), pageAo.getSize());

        if ( pageAo.getCurrent() != null )
            return new Page<>(pageAo.getCurrent(), DEFAULT_LIMIT);

        if ( pageAo.getSize() != null )
            return new Page<>(DEFAULT_PAGE_START, pageAo.getSize());

        return new Page<>(DEFAULT_PAGE_START, DEFAULT_LIMIT);
    }

    /**
     * 创建同层的分页对象
     * @param ao
     * @param records
     * @param <R>
     * @return
     */
    public static final <R> PageVo createSameLayer(PageAo ao, List<R> records) {
        return new RowBoundsSameLayerPageVo<R>(ao, records);
    }

    /**
     * 创建同层的分页对象
     * @param ao
     * @param supplier
     * @param <R>
     * @return
     */
    public static final <R> PageVo createSameLayer(PageAo ao, Supplier<List<R>> supplier) {
        return createSameLayer(ao, supplier.get());
    }

    /**
     * 创建同层的分页对象
     * @param ao
     * @param records
     * @param <R>
     * @return
     */
    public static final <R> RowBoundsPageVoRet<R> create(PageAo ao, List<R> records) {
        return new RowBoundsPageVoRet<>(ao, records);
    }

    /**
     * ..
     * @param ao
     * @param records
     * @param <R>
     * @return
     */
    public static final <R> RowBoundsPageVoRet<R> create(PageAo ao, Stream<R> records) {
        return create(ao, records.collect(Collectors.toList()));
    }

    /**
     * 创建同层的分页对象
     * @param ao
     * @param supplier
     * @param <R>
     * @return
     */
    public static final <R> RowBoundsPageVoRet<R> create(PageAo ao, Supplier<List<R>> supplier) {
        return create(ao, supplier.get());
    }

}
